<?php

namespace App\Service\Message;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Helpers\RedisUtil;
use App\Model\AccostLogs;
use App\Model\HostPushLog;
use App\Model\Message;
use App\Model\PayOrder;
use App\Model\User;
use App\Model\UserAutoMsg;
use App\Model\UserBlacklist;
use App\Model\UserChat;
use App\Model\UserProfile;
use App\Service\User\UserBaseService;

/**
 * 开启聊天
 */
class ChatStartService extends UserBaseService
{

    // public $newVersion = '1.1.3';

    protected function RoVerifyList()
    {
        return [
            'chat_user_id' => 'required|int'
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $chatUserId = $this->request->input('chat_user_id', 0);
        // $isNewVersion = $this->request->input('version', '1.0') >= $this->newVersion;

        //开启入口来源
        $from = $this->request->input('from', UserChat::FROM_MAIN_PAGE);

        if (!$chatUserId) return $this->setError(ErrorCode::PARAMETER_ERROR, '对方ID错误！');
        $user = User::getUser($chatUserId);
        if (!$user) return $this->setError(ErrorCode::PARAMETER_ERROR, '对方账号错误！');



        //用户资料
        $userProfile = UserProfile::getProfile($userId);
        $validAppIds = explode(',', env('CHAT_NO_LIMIT_APPID', 6));
        if ($userProfile->gender == 0 && !in_array($this->appId, $validAppIds)) {
            //女性检测是否实名，真人
//            $checkResult = $this->checkHostVrfy($userId, $userProfile);
            $checkResult = $this->checkHostVrfyV2($userId, $userProfile->created_at, $userProfile);
            if ($checkResult['errcode'] > 0) {
                return $this->setError($checkResult['errcode'], $checkResult['errmsg']);
            }
        }

        //获取对方资料
        $chatUserInfo = UserProfile::getProfile($chatUserId);
        if($userProfile->gender == $chatUserInfo->gender && !User::checkOfficial([$chatUserId, $userId])){
            return $this->setError(ErrorCode::NO_CHAT_SAME_GENDER, "暂不允许和对方聊天哦～");
        }


        //拉黑关系
        $checkBlack = UserBlacklist::check($chatUserId, $userId);
        if ($checkBlack) {
            return $this->setError(ErrorCode::CHAT_BLACK_LMT, '对方已经将你拉黑，暂无法聊天～');
        }

        //男性
        if ($userProfile->gender == 1) {
            //当天充值记录
            $checkRecharge = PayOrder::checkSuccess($userId, date('Y-m-d'));
            //今天开启聊天次数限制
            $chatStartTimes = UserChat::checkToday($userId);
            if (!check_dev_env() && !$checkRecharge && $chatStartTimes >= ConfigUtil::getChat('daily_times')) {
                return $this->setError(ErrorCode::CHAT_DAILY_LIMIT, "免费私聊次数已用完\n今天完成任意金额充值即可无限发送私信哦～");
            }
        }

        //加入记录
        $result = UserChat::addRecord($userId, $chatUserId, $from);
        $ret = [
            'result' => 1,
            'chat_im_account' => $user->im_account,
            'chat_user_version' => $user->version
        ];

        //自动招呼消息
        //对方是女性，不发送自动消息
        $chatProfile = UserProfile::getProfile($chatUserId);
        if ($chatProfile->gender == 0) {
            $ret['auto_msgs'] = [];
            $issetAutoMsg = 1;
        } else {
            $autoMsgs = $this->getAutoMsgs($userId, $chatUserId);
            $ret['auto_msgs'] = $autoMsgs['msgs'];
            $issetAutoMsg = $autoMsgs['isset'];
        }

        //女用户打招呼（上线提醒，主页列表搭讪）
        $autoFrom = [UserChat::FROM_ONLINE_TIP, UserChat::FROM_USER_LIST];
        if ($userProfile->gender == 0 && in_array($from, $autoFrom) && !$issetAutoMsg) {
            return $this->setError(ErrorCode::NO_AUTO_MSG, '没有设置自动回复消息');
        }

        //用户列表（主播主动搭讪）
        if ($from == UserChat::FROM_USER_LIST) {
            $this->doHostGreet($ret, $userId, $chatUserId);
        }
//        #添加记录
//        go(function () use($userId,$chatUserId){
//            $expiresTime = time()+86400;
//            AccostLogs::addRecord($userId,$chatUserId,$expiresTime);
//        });
        RedisUtil::set("chat_start_{$userId}_{$chatUserId}",1,86400);

        log_user_result($userId, "ChatUserId:{$chatUserId}==From:{$from}==Ret:" . json_encode($ret));
        return $ret;
    }

    /**
     * 主播首页搭讪
     */
    function doHostGreet(&$ret = [], $userId, $chatUserId)
    {
        $key = "chat_start_{$userId}_{$chatUserId}";
        if (RedisUtil::get($key) == 1) return;
        //设置为已经搭讪过
        RedisUtil::set($key, 1, 3600 * 24);
        //发送三件套
        $checkOffTime = env('HOST_PUSH_PACKAGE_OFFTIME', 3600 * 6);
        if (!HostPushLog::checkPushedCount($chatUserId, $checkOffTime, $userId)) {
            $result = Message::sendProfilePackage($chatUserId, $userId, 1);
            $ret['auto_msgs'] = [];
        } else {
            $msg = UserAutoMsg::pickOneMsg($userId, 'text');
            $ret['auto_msgs'] = $msg ? [$msg] : [];
        }
        return;
    }

    /**
     * 自动打招呼消息
     */
    function getAutoMsgs($userId = 0, $chatUserId = 0)
    {
        $autoMsgs = UserAutoMsg::pickMultiUserMsgs($userId);
        return ['isset' => !empty($autoMsgs) ? 1 : 0, 'msgs' => $autoMsgs];
    }

    //不检测限制
    function checkPass($from)
    {
        return $from == UserChat::FROM_REC_USER_CARD;
    }
}
